using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;

public class DoorFrame : NetworkBehaviour
{
	public Animator animator;

	[SyncVar(hook = "OnDoorOpen")]
	public bool IsOpen;

	private float timeTemp;

	public float Cooldown = 0.5f;

	public string DoorKey = string.Empty;

	public AudioSource audioSource;

	public bool NetworkIsOpen
	{
		get
		{
			return IsOpen;
		}
		[param: In]
		set
		{
			ref bool isOpen = ref IsOpen;
			if (NetworkServer.localClientActive && !base.syncVarHookGuard)
			{
				base.syncVarHookGuard = true;
				OnDoorOpen(value);
				base.syncVarHookGuard = false;
			}
			SetSyncVar(value, ref isOpen, 1u);
		}
	}

	private void Start()
	{
		if (audioSource == null)
		{
			audioSource = GetComponent<AudioSource>();
		}
		if (animator == null)
		{
			animator = GetComponent<Animator>();
		}
	}

	public override void OnStartClient()
	{
		OnDoorOpen(IsOpen);
		base.OnStartClient();
	}

	private void OnDoorOpen(bool open)
	{
		NetworkIsOpen = open;
		if ((bool)animator)
		{
			animator.SetBool("IsOpen", IsOpen);
		}
		if ((bool)audioSource)
		{
			audioSource.Play();
		}
	}

	public void Access(GameObject character)
	{
		AccessDoor(DoorKey);
	}

	private void AccessDoor(string key)
	{
		if (key == DoorKey && Time.time > timeTemp + Cooldown)
		{
			NetworkIsOpen = !IsOpen;
			timeTemp = Time.time;
		}
	}

	private void UNetVersion()
	{
	}

	public override bool OnSerialize(NetworkWriter writer, bool forceAll)
	{
		if (forceAll)
		{
			writer.Write(IsOpen);
			return true;
		}
		bool flag = false;
		if ((base.syncVarDirtyBits & 1) != 0)
		{
			if (!flag)
			{
				writer.WritePackedUInt32(base.syncVarDirtyBits);
				flag = true;
			}
			writer.Write(IsOpen);
		}
		if (!flag)
		{
			writer.WritePackedUInt32(base.syncVarDirtyBits);
		}
		return flag;
	}

	public override void OnDeserialize(NetworkReader reader, bool initialState)
	{
		if (initialState)
		{
			IsOpen = reader.ReadBoolean();
			return;
		}
		int num = (int)reader.ReadPackedUInt32();
		if ((num & 1) != 0)
		{
			OnDoorOpen(reader.ReadBoolean());
		}
	}
}
